package com.gome.axwl.aoc.web.controller.contract;

import com.gome.axwl.aoc.common.util.ErrorCode;
import com.gome.axwl.aoc.entity.TemplateRequest;
import com.gome.axwl.aoc.entity.dto.PageResultDto;
import com.gome.axwl.aoc.entity.exception.ZQException;
import com.gome.axwl.aoc.entity.po.ContractTemplatePo;
import com.gome.axwl.aoc.facade.ContractTemplateFacade;
import com.gome.axwl.aoc.facade.util.Base64Utils;
import com.gome.axwl.aoc.facade.util.DownloadFileUtil;
import com.gome.common.utils.StringUtil;
import com.gome.commons.core.ResultData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Base64;
import java.util.Date;
import java.util.List;

/**
 * Created by wanglongyu on 2018/7/16.
 */
@Api(tags = "合同模板")
@RestController
@RequestMapping(value = "/template")
public class ContractTemplateController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ContractTemplateFacade contractTemplateFacade;

    @ApiOperation(value = "分页查询模板信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "templateName",    value = "模板名称", paramType = "query",dataType="String"),
            @ApiImplicitParam(name = "pageNum",         value = "当前页", paramType = "query",dataType="int"),
            @ApiImplicitParam(name = "pageSize",        value = "当前页条数", paramType = "query",dataType="int")
    })
    @ResponseBody
    @RequestMapping(value = "/queryTemplate",method = RequestMethod.GET)
    public ResultData<PageResultDto<ContractTemplatePo>> queryTemplate(String templateName, Integer pageNum, Integer pageSize){
        return ResultData.newResultData(contractTemplateFacade.queryTemplate(templateName, pageNum, pageSize));
    }

    @ApiOperation(value = "下载合同模板")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "templateNo", value = "模板编码", paramType = "query",dataType="String"),
            @ApiImplicitParam(name = "templateName", value = "模板编码", paramType = "query",dataType="String"),
    })
    @ResponseBody
    @RequestMapping(value = "/download",method = RequestMethod.GET)
    public ResultData<Integer> download(String templateNo, String templateName,HttpServletResponse response){
        if(StringUtil.isBlank(templateNo)){
            return ResultData.newResultData(ErrorCode.PARAM_IS_NULL,ErrorCode.PARAM_IS_NULL_MSG);
        }
        String url = "";
        try {
            url = contractTemplateFacade.download(templateNo);
        } catch (ZQException e) {
            logger.debug("下载模板失败，失败原因[ {} ]",e.getMessage());
            return ResultData.newResultData(e.getCode(), e.getMessage());
        }
        InputStream inputStream = DownloadFileUtil.getFile(url);

        DownloadFileUtil.setResponseHeader(response,templateName+".pdf");
        OutputStream os;
        try {
            //获取自己的输入流数组
            byte[] getData = DownloadFileUtil.readInputStream(inputStream);
            os = response.getOutputStream();
            os.write(getData);
            os.flush();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  ResultData.newSuccessResultData();
    }



    @ApiOperation(value = "删除合同模板")
    @ResponseBody
    @RequestMapping(value = "/delete",method = RequestMethod.POST)
    public ResultData<Integer> delete(@RequestBody  TemplateRequest request){
        if(StringUtil.isBlank(request.getTemplateNo())){
            return ResultData.newResultData(ErrorCode.PARAM_IS_NULL,ErrorCode.PARAM_IS_NULL_MSG);
        }
        return ResultData.newResultData(contractTemplateFacade.delete(request.getTemplateNo()));
    }

    @ApiOperation(value = "获取所有合同模板")
    @ResponseBody
    @RequestMapping(value = "/queryAll",method = RequestMethod.GET)
    public ResultData<List<ContractTemplatePo>> queryAll(){
        return ResultData.newResultData(contractTemplateFacade.queryAll());
    }

    @ApiOperation(value = "更新合同模板")

    @ResponseBody
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public ResultData<Integer> update(@RequestBody  TemplateRequest request){
        if(validate(request.getTemplateNo(), request.getTemplateName(), request.getProperty(), request.getSignWay())){
            return ResultData.newResultData(ErrorCode.PARAM_IS_NULL,ErrorCode.PARAM_IS_NULL_MSG);
        }
        return ResultData.newResultData(contractTemplateFacade.update(request.getTemplateNo(), request.getTemplateName(), request.getProperty(), request.getSignWay()));
    }

    /**
     * 更新模板参数校验
     * @param templateNo
     * @param templateName
     * @param property
     * @param signWay
     * @return
     */
    private boolean validate(String templateNo,String templateName,String property,Integer signWay){
        if(StringUtil.isBlank(templateNo)){
            return true;
        }
        if(StringUtil.isBlank(templateName)){
            return true;
        }
        if(StringUtil.isBlank(property)){
            return true;
        }
        if(signWay == null){
            return true;
        }
        return false;
    }
//    @ApiOperation(value = "选择模板生成空白合同（送签）")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "applyInfoId",     value = "申请单号id",   paramType = "form",dataType="int"),
//            @ApiImplicitParam(name = "templateNo",      value = "模板编码",     paramType = "form",dataType="String"),
//            @ApiImplicitParam(name = "contractName",    value = "合同名称",     paramType = "form",dataType="String")
//    })
//    @ResponseBody
//    @RequestMapping(value = "/buildEmptyContract",method = RequestMethod.POST)
//    public ResultData<Integer> buildEmptyContract(Integer applyInfoId,String templateNo,String contractName){
//        if(applyInfoId == null || StringUtil.isBlank(templateNo) || StringUtil.isBlank(contractName)){
//            return ResultData.newResultData(ErrorCode.PARAM_IS_NULL,ErrorCode.PARAM_IS_NULL_MSG);
//        }
//        return ResultData.newResultData(contractTemplateFacade.buildEmptyContract(applyInfoId, templateNo, contractName));
//    }

    @ApiOperation(value = "添加合同模板")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "signWay",       value = "签署方式1-自动签署2-手动签署",   paramType = "form",dataType="int"),
            @ApiImplicitParam(name = "property",      value = "性质",     paramType = "form",dataType="String"),
            @ApiImplicitParam(name = "templateName",  value = "模板名称",     paramType = "form",dataType="String")
    })
    @ResponseBody
    @RequestMapping(value = "/addTemplate",method = RequestMethod.POST)
    public ResultData<Integer> addTemplate(@RequestParam("file") MultipartFile file, Integer signWay, String property, String templateName){
        if(signWay == null || StringUtil.isBlank(property) || StringUtil.isBlank(templateName)){
            return ResultData.newResultData(ErrorCode.PARAM_IS_NULL,ErrorCode.PARAM_IS_NULL_MSG);
        }
        String fileName = file.getOriginalFilename();
        if(!fileName.endsWith(".pdf")){
            return ResultData.newResultData(ErrorCode.PDF_ONLY,ErrorCode.PDF_ONLY_MSG);
        }
        byte[] inputByte;
        String base64 = "";
        try {
            inputByte = Base64Utils.input2byte(file.getInputStream());
            base64 = Base64Utils.encode(inputByte);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            return ResultData.newResultData(contractTemplateFacade.addTemplate(base64,property,signWay,templateName));
        } catch (ZQException e) {
            logger.debug("添加模板失败，失败原因[ {} ]",e.getMessage());
            return ResultData.newResultData(e.getCode(), e.getMessage());
        }
    }
}
